package test.design.chain.servlet;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import test.design.chain.Request;
import test.design.chain.Response;

public class Chain {
	
	List<Filter> filters = new ArrayList<>();
	int index;
	
	public Chain addFilter(Filter filter) {
		filters.add(filter);
		return this;
	}
	
	public void doFilter(Request request, Response response) {
		if(index < filters.size()) {
			filters.get(index++).doFilter(request, response, this);
		}
//		for(Filter filter : filters) {
//			filter.doFilter(request, response, this);
//		}
	}
	
	public void process(Object obj, String method, Request request, Response response) {
		doFilter(request, response);
		try {
			obj.getClass().getMethod(method, new Class[] {Request.class, Response.class}).invoke(obj, request, response);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}

}
